-
Notifications
You must be signed in to change notification settings - Fork 0
/
html_helpers.c
86 lines (73 loc) · 2.13 KB
/
html_helpers.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// Created by lemito on 5/15/24.
//
#include "html_helpers.h"
char *text_creator(const char *message)
{
size_t message_len = strlen(message);
size_t response_len = message_len + 8;
char *response = malloc(response_len);
if (response == NULL)
{
fprintf(stderr, "Не удалось создать response");
return NULL;
}
snprintf(response, response_len, "<p>%s</p>", message);
return response;
}
char *form_creator(const char *action, char *const value, char *const id)
{
char *response = malloc(1024);
snprintf(response, 1024, "<form action='%s' method='post'><input value='%s' id='%s' type='text' name='name' /><button type='submit'>Submit</button></form>", action, value, id);
return response;
}
void html_raw(int sockfd, const char* data, size_t size){
if (write(sockfd, data, size) < 0)
fprintf(stderr, "Ошибка записи html вывода");
}
void html(int sockfd, const char *txt)
{
size_t txt_len = strlen(txt);
html_raw(sockfd, txt, txt_len);
}
void html_attr(int sockfd, const char *txt)
{
const char *t = txt;
while (t && *t) {
int c = (int)*t;
if (c == '<' || c == '>' || c == '\'' || c == '\"' || c == '&') {
html_raw(sockfd, txt, t - txt);
if (c == '>')
html(sockfd, ">");
else if (c == '<')
html(sockfd, "<");
else if (c == '\'')
html(sockfd, "'");
else if (c == '"')
html(sockfd, """);
else html(sockfd, "&");
txt = t + 1;
}
t++;
}
if (t != txt)
html(sockfd, txt);
}
__attribute__((unused)) void html_link_open(int sockfd, const char *url, const char *title, const char *class)
{
html(sockfd, "<a href='");
html_attr(sockfd, url);
if (title) {
html(sockfd, "' title='");
html_attr(sockfd, title);
}
if (class) {
html(sockfd, "' class='");
html_attr(sockfd, class);
}
html(sockfd, "'>");
}
__attribute__((unused)) void html_link_close(int sockfd)
{
html(sockfd, "</a>");
}