Commit 47736d3d authored by Muhammad, Hammad's avatar Muhammad, Hammad

used http module

parent 771caf72
module hello_world
go 1.20
......@@ -2,36 +2,27 @@ package main
import (
"fmt"
"strings"
"io"
"net/http"
"os"
)
func main() {
str := ToSnakeCase("helloWorld !!!")
fmt.Println(str)
}
func ToSnakeCase(str string) string {
// step 0: handle empty string
if str == "" {
return ""
}
type logWriter struct{}
// step 1: CamelCase to snake_case
for i := 0; i < len(str); i++ {
if str[i] >= 'A' && str[i] <= 'Z' {
if i == 0 {
str = strings.ToLower(string(str[i])) + str[i+1:]
} else {
str = str[:i] + "_" + strings.ToLower(string(str[i])) + str[i+1:]
}
}
func main() {
resp, err := http.Get("http://google.com")
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
// step 2: remove spaces
str = strings.ReplaceAll(str, " ", "")
lw := logWriter{}
// step 3: remove double-underscores
str = strings.ReplaceAll(str, "__", "_")
io.Copy(lw, resp.Body)
}
return str
func (logWriter) Write(bs []byte) (int, error) {
fmt.Println(string(bs))
fmt.Println("Just wrote this many bytes:", len(bs))
return len(bs), nil
}
package main
import "testing"
func TestToSnakeCase(t *testing.T) {
type testCase struct {
description string
input string
expected string
}
testCases := []testCase{
{
description: "empty string",
input: "",
expected: "",
},
{
description: "single word",
input: "Hello",
expected: "hello",
},
{
description: "two words (camel case)",
input: "HelloWorld",
expected: "hello_world",
},
{
description: "two words with space",
input: "Hello World",
expected: "hello_world",
},
{
description: "two words with space and underscore",
input: "Hello_World",
expected: "hello_world",
},
}
for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
actual := ToSnakeCase(tc.input)
if actual != tc.expected {
t.Errorf("expected %s, got %s", tc.expected, actual)
}
})
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment