-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: anish bista <[email protected]>
- Loading branch information
1 parent
1896243
commit a445a3d
Showing
3 changed files
with
255 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
module github.com/anishbista60/Devops-project | ||
|
||
go 1.22.5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
package main | ||
|
||
import ( | ||
"embed" | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"path" | ||
"sync" | ||
) | ||
|
||
var ( | ||
names = []string{} | ||
namesMutex sync.Mutex | ||
) | ||
|
||
//go:embed static/* | ||
var staticFiles embed.FS | ||
|
||
func main() { | ||
http.HandleFunc("/", handleIndex) | ||
http.HandleFunc("/ping", pingHandler) | ||
http.HandleFunc("/add", handleAdd) | ||
http.HandleFunc("/delete", handleDelete) | ||
http.HandleFunc("/names", handleNames) | ||
//http.Handle("/static/", http.FileServer(http.Dir(os.Getenv("KO_DATA_PATH")))) | ||
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFiles)))) | ||
|
||
log.Println("Starting server on :8000") | ||
if err := http.ListenAndServe(":8000", nil); err != nil { | ||
log.Fatalf("Could not start server: %s\n", err) | ||
} | ||
} | ||
|
||
func pingHandler(w http.ResponseWriter, r *http.Request) { | ||
fmt.Fprintln(w, "Pong!") | ||
} | ||
|
||
func handleIndex(w http.ResponseWriter, r *http.Request) { | ||
log.Println("Serving index.html") | ||
indexPath := path.Join("static", "index.html") | ||
content, err := staticFiles.ReadFile(indexPath) | ||
if err != nil { | ||
log.Printf("Error reading index.html: %v", err) | ||
http.Error(w, "Page not found", http.StatusNotFound) | ||
return | ||
} | ||
w.Write(content) | ||
} | ||
|
||
func handleAdd(w http.ResponseWriter, r *http.Request) { | ||
log.Println("Handling add request") | ||
if r.Method == "POST" { | ||
log.Println("Received POST request to add name") | ||
log.Printf("Content-Type: %s", r.Header.Get("Content-Type")) | ||
if err := r.ParseMultipartForm(10 << 20); err != nil { // 10MB limit | ||
log.Println("Error parsing multipart form:", err) | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
name := r.FormValue("name") | ||
log.Printf("Received name: %s", name) | ||
if name != "" { | ||
namesMutex.Lock() | ||
names = append(names, name) | ||
namesMutex.Unlock() | ||
log.Println("Added name:", name) | ||
log.Println("Current names:", names) | ||
} else { | ||
log.Println("Name is empty, not adding") | ||
} | ||
jsonResponse(w, names) | ||
} else { | ||
log.Println("Invalid request method for add") | ||
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) | ||
} | ||
} | ||
|
||
func handleDelete(w http.ResponseWriter, r *http.Request) { | ||
log.Println("Handling delete request") | ||
if r.Method == "POST" { | ||
log.Println("Received POST request to delete name") | ||
if err := r.ParseMultipartForm(10 << 20); err != nil { // 10MB limit | ||
log.Println("Error parsing multipart form:", err) | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
name := r.FormValue("name") | ||
log.Println("Received name to delete:", name) | ||
namesMutex.Lock() | ||
for i, n := range names { | ||
if n == name { | ||
names = append(names[:i], names[i+1:]...) | ||
break | ||
} | ||
} | ||
namesMutex.Unlock() | ||
log.Println("Deleted name:", name) | ||
log.Println("Current names:", names) | ||
jsonResponse(w, names) | ||
} else { | ||
log.Println("Invalid request method for delete") | ||
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) | ||
} | ||
} | ||
|
||
func handleNames(w http.ResponseWriter, r *http.Request) { | ||
log.Println("Handling names request") | ||
jsonResponse(w, names) | ||
log.Println("Current names:", names) | ||
} | ||
|
||
func jsonResponse(w http.ResponseWriter, data interface{}) { | ||
w.Header().Set("Content-Type", "application/json") | ||
if data == nil { | ||
log.Println("jsonResponse data is nil") | ||
} else { | ||
log.Println("jsonResponse data:", data) | ||
} | ||
if err := json.NewEncoder(w).Encode(data); err != nil { | ||
log.Println("Error encoding JSON:", err) | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
<title>Go Server Example</title> | ||
<style> | ||
body { | ||
font-family: Arial, sans-serif; | ||
} | ||
.logo { | ||
display: block; | ||
margin: 20px auto; | ||
width: 100px; | ||
} | ||
form { | ||
text-align: center; | ||
margin: 20px 0; | ||
} | ||
ul { | ||
list-style: none; | ||
padding: 0; | ||
text-align: center; | ||
} | ||
li { | ||
margin: 10px 0; | ||
} | ||
</style> | ||
</head> | ||
<body> | ||
<img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" alt="Logo" class="logo"> | ||
<form id="addForm"> | ||
<input type="text" id="nameInput" name="name" placeholder="Enter name" required> | ||
<button type="submit">Add Name</button> | ||
</form> | ||
<ul id="nameList"></ul> | ||
<script> | ||
async function fetchNames() { | ||
const response = await fetch('/names'); | ||
if (response.ok) { | ||
const names = await response.json(); | ||
console.log('Fetched names:', names); | ||
if (!names) { | ||
console.error('Fetched names is null'); | ||
return; | ||
} | ||
updateNameList(names); | ||
} else { | ||
console.error('Failed to fetch names:', response.statusText); | ||
} | ||
} | ||
|
||
function updateNameList(names) { | ||
if (!Array.isArray(names)) { | ||
console.error('Names is not an array:', names); | ||
return; | ||
} | ||
const nameList = document.getElementById('nameList'); | ||
nameList.innerHTML = ''; | ||
names.forEach(name => { | ||
const li = document.createElement('li'); | ||
li.textContent = name; | ||
const deleteForm = document.createElement('form'); | ||
deleteForm.action = '/delete'; | ||
deleteForm.method = 'post'; | ||
deleteForm.style.display = 'inline'; | ||
deleteForm.innerHTML = ` | ||
<input type="hidden" name="name" value="${name}"> | ||
<button type="submit">Delete</button> | ||
`; | ||
deleteForm.addEventListener('submit', async (event) => { | ||
event.preventDefault(); | ||
const formData = new FormData(deleteForm); | ||
const response = await fetch('/delete', { | ||
method: 'POST', | ||
body: formData | ||
}); | ||
if (response.ok) { | ||
const updatedNames = await response.json(); | ||
console.log('Updated names after delete:', updatedNames); | ||
updateNameList(updatedNames); | ||
} else { | ||
console.error('Failed to delete name:', response.statusText); | ||
} | ||
}); | ||
li.appendChild(deleteForm); | ||
nameList.appendChild(li); | ||
}); | ||
} | ||
|
||
document.getElementById('addForm').addEventListener('submit', async (event) => { | ||
event.preventDefault(); | ||
const nameInput = document.getElementById('nameInput'); | ||
const name = nameInput.value.trim(); | ||
if (name === '') { | ||
console.error('Name input is empty'); | ||
return; | ||
} | ||
const formData = new FormData(); | ||
formData.append('name', name); | ||
console.log('FormData being sent:', formData); | ||
for (let [key, value] of formData.entries()) { | ||
console.log(key, value); | ||
} | ||
const response = await fetch('/add', { | ||
method: 'POST', | ||
body: formData | ||
}); | ||
if (response.ok) { | ||
const names = await response.json(); | ||
console.log('Updated names after add:', names); | ||
if (!names) { | ||
console.error('Updated names after add is null'); | ||
return; | ||
} | ||
updateNameList(names); | ||
event.target.reset(); | ||
} else { | ||
console.error('Failed to add name:', response.statusText); | ||
} | ||
}); | ||
|
||
// Fetch initial names on page load | ||
fetchNames(); | ||
</script> | ||
</body> | ||
</html> |