Server-Side Scripting/Requests/Go

From Wikiversity
Jump to navigation Jump to search

server.go[edit | edit source]

// 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>&nbsp;</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 = 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
    } else if request.Method == "POST" {
        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
        }
    }

    io.WriteString(response, result)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8000", nil)
}

Try It[edit | edit source]

Copy and paste the code above into the following free online development environment or use your own Go compiler / interpreter / IDE.