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
+5.4k Linux : Disable and enable IPv4 forwarding
+4.7k Golang : Check if a word is countable or not
+7.1k Golang : Detect sample rate, channels or latency with PortAudio
+7.2k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+9.2k Golang : Copy map(hash table) example
+8.6k Golang : Inject/embed Javascript before sending out to browser example
+9.2k Javascript : Read/parse JSON data from HTTP response
+21.3k Golang : Use TLS version 1.2 and enforce server security configuration over client
+23.2k Golang : Fix type interface{} has no field or no methods and type assertions example
+30.8k Golang : How to convert(cast) string to IP address?
+24.4k Golang : Create PDF file from HTML file
+17.4k Golang : How to log each HTTP request to your web server?