A Go module to help with creating and managing servers.
To install, on Terminal or Command Prompt, run go get github.com/MJP8/servers
. Include it in your program like this:
package main
import (
"github.com/MJP8/servers/http"
)
func main() {
err := http.Init(8080)
if err != nil {
return
}
http.HandleStaticFile("/", "index.html", "text/html")
http.Serve()
}
const ( // error codes
InternalServerError = 500 // when you run the Error() function only InternalServerError will send the error to the browser
NotFoundError = 404
PathError = 402
FileError = 336
)
Error()
return a *ServerError
.
HandleCustom()
adds a handler for the URL specified. It runs the callback in the cb
parameter.
HandleStaticFile()
adds a handler for the URL, sending the data in the file.
HandleTemplate()
adds a handler for the URL specified, sending the template to the browser. See type Template
for more information
Init()
initiates the server. The parameter port
is the port for your server.
RenderTemplate()
renders the specified template. Used for inside the callback in the HandleCustom()
function.
Serve()
starts the web server using the port set in the Init()
function.
type Request = http.Request
Request
defines a HTTP request from the net/http
library.
type ResponseWriter = http.ResponseWriter
ResponseWriter
creates a HTTP response from the net/http
library.
type ServerError struct {
Code int
Msg string
}
ServerError
defines an error.
Converts a ServerError
into an variable of type error
.
type Template struct {
Filename string
Value interface{}
}
Template
defines a HTML template.
NewTemplate()
creates a new *Template
.
Example:
package main
import (
"time"
"github.com/MJP8/servers/http"
)
func main() {
err := http.Init(8080)
if err != nil {
return
}
tmpl := NewTemplate("index.html", time.Now().Format("15:04"))
http.HandleTemplate("/", tmpl)
http.Serve()
}