Golang : HTTP Server Example
Simple tutorial on HTTP server examples with Golang. Run the codes below and point your browser to http://localhost:8080
or http://localhost:8080/replyname/yourname
for example 2.
Example 1:
package main
import (
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Example 2:
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.1k Golang : Play .WAV file from command line
+17.4k Golang : Read data from config file and assign to variables
+23k Golang : Get ASCII code from a key press(cross-platform) example
+14.8k Golang : Save(pipe) HTTP response into a file
+19.6k Golang : Count JSON objects and convert to slice/array
+6.6k Golang : How to solve "too many .rsrc sections" error?
+7.9k Golang : Tell color name with OpenCV example
+6.9k Golang : A simple forex opportunities scanner
+5.4k Fix fatal error: evacuation not done in time problem
+18.6k Golang : Delete duplicate items from a slice/array
+23.3k Find and replace a character in a string in Go
+5.9k Java : Human readable password generator