-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c84ba9b
commit 868206c
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package nginxconf | ||
|
||
import "os" | ||
|
||
// File represents a nginx config file. | ||
// It wraps os.File | ||
type File struct { | ||
*os.File | ||
} | ||
|
||
// OpenFile opens a nginx config file for writing only. | ||
// If the file does not exist at that path, it is created | ||
// with the permissions 0666. | ||
func OpenFile(path string) (*File, error) { | ||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &File{f}, nil | ||
} | ||
|
||
// WriteDirective writes one directive to the file. | ||
// Call this function for each directive to write. | ||
func (f *File) WriteDirective(d *Directive) error { | ||
b := []byte(d.String() + "\n") | ||
_, err := f.Write(b) | ||
if err != nil { | ||
return err | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package nginxconf | ||
|
||
import ( | ||
"fmt" | ||
"io/ioutil" | ||
"os" | ||
"testing" | ||
) | ||
|
||
func TestOpenFile(t *testing.T) { | ||
f, err := OpenFile("example.conf") | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
listen := NewDirective("listen", "80") | ||
err = f.WriteDirective(listen) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
sname := NewDirective("server_name", "example.com", "www.example.com") | ||
err = f.WriteDirective(sname) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
f.Close() | ||
|
||
rf, err := os.OpenFile("example.conf", os.O_RDONLY, 0666) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
b, err := ioutil.ReadAll(rf) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
expected := fmt.Sprintf("%s\n%s\n", listen, sname) | ||
|
||
if string(b) != expected { | ||
t.Fail() | ||
} | ||
|
||
err = os.Remove("example.conf") | ||
if err != nil { | ||
panic(err) | ||
} | ||
} |