git.sophuwu.com > urlshort
main function complete
sophuwu sophie@sophuwu.site
Fri, 01 Sep 2023 02:32:35 +0100
commit

b1cc38ea8d8cd9027d595ece5ab36fcc19eb1cdf

parent

e1c182f0a18d93d73a3613ad5e607f0c74a023bf

1 files changed, 36 insertions(+), 1 deletions(-)

jump to
M main.gomain.go

@@ -1,12 +1,14 @@

package main import ( + "context" "encoding/json" "errors" bolt "go.etcd.io/bbolt" "math/rand" "net/http" "os" + "os/signal" "strings" "time" )

@@ -186,7 +188,7 @@ err = r.ParseForm()

if hec(w, err, 500) { return } - if r.Form.Get("api") != "" { + if r.Form.Get("mode") == "api" { api = true } url.url = r.Form.Get("url")

@@ -224,6 +226,7 @@ createHandler(w, r)

return } http.ServeFile(w, r, "html/index.html") + return } path := strings.TrimSuffix(r.URL.Path[1:], "/") var err error

@@ -256,6 +259,38 @@ _ = writeURL(url)

} func main() { + var ( + port string = ":8088" + err error + server http.Server + ) + + if len(os.Args) == 2 { + port = ":" + os.Args[1] + } + + println("Starting server on port " + port) + openFiles() + http.HandleFunc("/", httpHandler) + + server = http.Server{ + Addr: port, + Handler: nil, + } + + go func() { + err = server.ListenAndServe() + if err != http.ErrServerClosed && err != nil { + urlDB.Close() + panic(err) + } + }() + quit := make(chan os.Signal, 1) + signal.Notify(quit, os.Interrupt) + <-quit + + urlDB.Close() + server.Shutdown(context.Background()) }