< Server-Side Scripting < Requests
server.go
// Converts a Fahrenheit temperature to Celsius using a GET request and
// converts a Celsius temperature to Fahrenheit using a POST request.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://golang.org/doc/
// https://golangcode.com/get-a-url-parameter-from-a-request/
// https://gowebexamples.com/forms/
package main
import (
"fmt"
"io"
"net/http"
"strconv"
)
var GET_FORM = `
<form method="GET">
<label for="fahrenheit">Enter Fahrenheit temperature:</label>
<input type="text" id="fahrenheit" name="fahrenheit">
<input type="submit" value="Submit">
</form>
`
var EMPTY_PARAGRAPH = `
<p> </p>
`
var POST_FORM = `
<form method="POST">
<label for="celsius">Enter Celsius temperature:</label>
<input type="text" id="celsius" name="celsius">
<input type="submit" value="Submit">
</form>
`
func handler(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "text/html; charset=utf-8")
result := ""
if request.Method == "GET" {
result = processGetRequest(request)
} else if request.Method == "POST" {
result = processPostRequest(request)
}
io.WriteString(response, result)
}
func processGetRequest(request *http.Request) string {
result := GET_FORM;
parameters := request.URL.Query()["fahrenheit"]
if len(parameters) > 0 {
fahrenheit, err := strconv.ParseFloat(parameters[0], 32)
if err == nil {
celsius := (fahrenheit - 32) * 5.0 / 9.0
result += fmt.Sprintf("<p>%f° Fahrenheit is %f° Celsius</p>",
fahrenheit, celsius)
} else {
result += EMPTY_PARAGRAPH
}
} else {
result += EMPTY_PARAGRAPH
}
result += POST_FORM + EMPTY_PARAGRAPH
return result
}
func processPostRequest(request *http.Request) string {
result := GET_FORM + EMPTY_PARAGRAPH + POST_FORM
value := request.FormValue("celsius")
celsius, err := strconv.ParseFloat(value, 32)
if err == nil {
fahrenheit := celsius * 9.0 / 5.0 + 32
result += fmt.Sprintf("<p>%f° Celsius is %f° Fahrenheit</p>",
celsius, fahrenheit)
} else {
result += EMPTY_PARAGRAPH
}
return result;
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
Try It
Copy and paste the code above into the following free online development environment or use your own Go compiler / interpreter / IDE.
This article is issued from Wikiversity. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.