68 lines
1.3 KiB
Markdown
68 lines
1.3 KiB
Markdown
# http package stuff
|
|
|
|
## HTTP Status Code
|
|
|
|
Do not use number directly.
|
|
|
|
Don't do this
|
|
|
|
```golang
|
|
w.WriteHeader(404)
|
|
```
|
|
|
|
Do this
|
|
|
|
```golang
|
|
w.WriteHeader(http.StatusNotFound)
|
|
```
|
|
|
|
## Error message
|
|
|
|
```golang
|
|
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
|
```
|
|
|
|
## Flusher
|
|
|
|
A [Flusher](https://pkg.go.dev/net/http#Flusher) can be used to allow an HTTP handler to flush buffered data to the client.
|
|
|
|
```golang
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
ended := make(chan bool)
|
|
f, flushable := w.(http.Flusher)
|
|
if flushable {
|
|
go func() {
|
|
ticker := time.NewTicker(1 * time.Second)
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
fmt.Println("debug")
|
|
io.WriteString(w, "#")
|
|
f.Flush()
|
|
case <-ended:
|
|
return
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
time.Sleep(5 * time.Second)
|
|
ended <- true
|
|
w.Write([]byte("ok"))
|
|
})
|
|
|
|
http.ListenAndServe(":8080", nil)
|
|
}
|
|
```
|